import { useEffect, useRef } from "react"
import { studyRecord } from "renderer/services/api"
import { getPlayerUrl } from "renderer/utils/helps"
import useGlobal from '../hooks/useGlobal'
import CmcPlayer from '../libs/cmcPlayer/cmcPlayer.js'

let player: any = null

interface PlayerProps {
  // on
}

let pollTime: NodeJS.Timeout

const playTime: {
  id: Number | undefined
  time: Number
} = {
  id: undefined,
  time: 0
}


export default function Player(props: PlayerProps) {

  const { playTask, user, config } = useGlobal()
  const prevUrlRef = useRef(playTask ? playTask : undefined)

  const playerRef = useRef<HTMLDivElement>(null)

  const sendStudyRecord = async (time: number, state: string = '', extra: boolean = false) => {

    const params = {
      //用户名
      username: user.name,
      //租户id
      user_id: user.id,
      tenant_code: user.tenant_id,
      //开始学习和学习中的标识
      type: extra ? 'learn' : 'learn_time',
      //课程id
      course_id: prevUrlRef.current?.course_id,
      //章节id
      course_subject_id: prevUrlRef.current?.sub_id,
      learn_time: 10,
      play_time: Math.floor(time),
      token: user.token,
      force: state ? 1 : undefined
    }

    studyRecord(params)
      .then(resp => {
        // console.log('study record resp =', resp)
        if(resp && resp.data && !resp.data.success) {
          window.electron.log.error('study record [error]: ', resp)
        }
      })
      .catch(err => {
        console.log('study record err =', err)
        window.electron.log.error('study record [error]: ', err)
      })

  }

  const pollPlayTime = () => {
    clearTimeout(pollTime)

    pollTime = setTimeout(() => {
      // console.log('pollPlayTime')
      // 学习中 
      const time = player.getPlayTime()
      sendStudyRecord(time)

      pollPlayTime()
    }, 10000)

  }


  useEffect(() => {
    // console.log('playerRef =', playerRef)
    // console.log('playTime/playTask =', playTime, playTask, )
    const vars = {
      fileHost: '/',
      width: '100%',
      height: '100%',
      mediaType: '5',
      svgIcon: true,
      autoPlay: true,
      withCredentials: true,
      resumeTime: (playTime.id && playTask && playTask.id &&  playTime.id === playTask.id) ? playTime.time : 0,
      // 音频增益
      audioGain: 5,
      url: getPlayerUrl(playTask, config.port),

      onPlayStatus: (status: string, playerId: string, data: any) => {
        // console.log('onPlayStatus =',status, playerId, data)
        if(data && data.response) {
          window.electron.log.error(`player [error]: ${JSON.stringify(data.response)} [playTask]: ${JSON.stringify(playTask)}` )
        }
        if(data && data.response &&  data.response.code === 401 && data.response.text === "UNAUTHORIZED") {
          //播放m3u8失败，由于token过期引起，提示用户重新登陆
          window.electron.ipcRenderer.login()

          clearTimeout(pollTime)

          return
        } 

        if(status === 'pause') {
          const time = player.getPlayTime()
          // console.log('pause study')
          sendStudyRecord(time, 'pause')
        }

        if(status === 'playing') {
          pollPlayTime()
        } else {
          clearTimeout(pollTime)
        }
      },

      onTimeUpdate: (time: number) => {
        playTime.time = time
      }
      
    }

    // console.log('player start play =', playTask)

    player = new CmcPlayer('playerBox', vars)

    // 如果有视频地址，则发送进入观看
    if(vars.url !== '') {
      // 开始学习
      // console.log('start study')
      sendStudyRecord(0, '', true)

      playTime.id = playTask?.id
    }

    return () => {
      clearTimeout(pollTime)
      player.destroy()
      player = null
      // player.pausePlay()
    }

  }, [])

  useEffect(() => {

    if(player && playTask) {
      // 开启新播放
      if(prevUrlRef.current !== playTask) {
        prevUrlRef.current = playTask
        // console.log('player change play =', playTask.localUrl)
        player.playerPlay({
          url: getPlayerUrl(playTask, config.port)
        });
        // 开始学习
        // console.log('start study')
        sendStudyRecord(0, '', true)

        playTime.id = playTask.id
      } else {
        // 继续播放
        // player.resumePlay()
      }
      
    }

  }, [playTask])

  // console.log('player render ==', playTask)

  return (
    <div className="player-box" id="playerBox" ref={playerRef} ></div>
  )
}